﻿
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Services.BASE;
using XiangziProjectTemplete.Core.IRepository.Base;
using System.Threading.Tasks;
using XiangziProjectTemplete.Core.Model.CommonModel;
using System.Linq;

namespace XiangziProjectTemplete.Core.Services
{
    /// <summary> 
    /// 生成任务号表服务接口实现 
    /// </summary>	 
    public class Base_GenerateTaskNoServices : BaseServices<Base_GenerateTaskNo>, IBase_GenerateTaskNoServices
    {
        private readonly IBaseRepository<Base_GenerateTaskNo> _dal;
        public Base_GenerateTaskNoServices(IBaseRepository<Base_GenerateTaskNo> dal)
        {
            this._dal = dal;
            base.BaseDal = dal;
        }

        /// <summary>
        /// 生成新的任务号
        /// </summary>
        /// <param name="generateTaskType"></param>
        /// <returns></returns>
        public async Task<FunReturnResultModel<string>> GenerateTaskNo(int generateTaskType)
        {
            FunReturnResultModel<string> funReturnResultModel = new FunReturnResultModel<string>();
            try
            {
                var queryDataList = await _dal.Query(x => x.GenerateTaskType == generateTaskType);
                if (queryDataList == null || queryDataList.Count == 0)
                {
                    funReturnResultModel.IsSuccess = false;
                    funReturnResultModel.ErrMsg = "没有找到任务类型为" + generateTaskType + "的基础数据";
                    return funReturnResultModel;
                }
                if (queryDataList.Count > 1)
                {
                    funReturnResultModel.IsSuccess = false;
                    funReturnResultModel.ErrMsg = "找到" + queryDataList.Count + "条任务类型为" + generateTaskType + "的基础数据";
                    return funReturnResultModel;
                }
                var targetData = queryDataList.First();
                var oldTaskId = targetData.GenerateTaskId;
                targetData.GenerateTaskId += 1;
                var newTaskNo = targetData.GenerateTaskNoPrefix + targetData.GenerateTaskId;
                targetData.GenerateTaskNo = newTaskNo;
                targetData.OperationRemark = "新生成任务号，旧任务号为" + targetData.GenerateTaskNoPrefix + oldTaskId;
                targetData.ModifyTime = System.DateTime.Now;
                await _dal.Update(targetData);

                funReturnResultModel.IsSuccess = true;
                funReturnResultModel.data = newTaskNo;
                return funReturnResultModel;

            }
            catch (System.Exception)
            {
                throw;
            }
        }
    }
}
